from fastapi import APIRouter, Form, Request
from fastapi.templating import Jinja2Templates
import ntplib

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/time/offset/calculator")
async def get_offset_calculator(request: Request):
    c = ntplib.NTPClient()
    res = c.request("time.windows.com")
    db_offset = res.offset * 1000
    return templates.TemplateResponse("offset-calculator.html", {
        "request": request,
        "db_offset": db_offset,
    })


@router.post("/time/offset/calculator")
async def get_offset_calculator_result(request: Request, db_offset: str = Form(...), local_offset: str = Form(...)):
    final_offset = float(db_offset) - float(local_offset) * 1000
    return templates.TemplateResponse("offset-calculator-result.html", {
        "request": request,
        "final_offset": final_offset,
    })
